package com.lyw.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyw.forum.common.enums.ResultCode;
import com.lyw.forum.common.exception.ApplicationException;
import com.lyw.forum.common.utils.BeanTransUtils;
import com.lyw.forum.common.utils.JWTUtils;
import com.lyw.forum.common.utils.MD5Utils;
import com.lyw.forum.common.utils.UUIDUtil;
import com.lyw.forum.mapper.UserMapper;
import com.lyw.forum.pojo.dataobject.User;
import com.lyw.forum.pojo.request.ModifyPasswordRequest;
import com.lyw.forum.pojo.request.UserLoginRequest;
import com.lyw.forum.pojo.request.UserModifyRequest;
import com.lyw.forum.pojo.request.UserRegisterRequest;
import com.lyw.forum.pojo.response.AppResult;
import com.lyw.forum.pojo.response.UserLoginResponse;
import com.lyw.forum.pojo.response.UserSelectResponse;
import com.lyw.forum.service.IUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(UserRegisterRequest userRegisterRequest) {
        //1.非空校验
        if (userRegisterRequest == null || !StringUtils.hasLength(userRegisterRequest.getUsername())) {
            //打印日志
            log.error("用户名不能为空");
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2.按照用户名查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername, userRegisterRequest.getUsername()).eq(User::getState, 0)
                            .eq(User::getDeleteState, 1);
        User existUser = userMapper.selectOne(queryWrapper);

        //2.1 判断用户是否存在
        if (existUser != null) {
            //打印日志
            log.error("用户已存在");
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_EXISTS));
        }

        //3.新增用户, 设置默认值(减少数据库的压力)
        User user = BeanTransUtils.transUser(userRegisterRequest);
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);

        //当前日期
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);

        //4.处理密码
        //4.1.生成盐
        String salt = UUIDUtil.UUID_32();
        //4.2.密码加密
        String encryptPassword = MD5Utils.md5Salt(user.getPassword(), salt);
        //4.3.设置密码和盐
        user.setPassword(encryptPassword);
        user.setSalt(salt);

        //5.插入用户
        int row = userMapper.insert(user);

        if (row != 1) {
            //打印日志
            log.error(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        //打印日志
        log.info("用户创建成功, username: " + user.getUsername());

    }

    @Override
    public UserLoginResponse login(UserLoginRequest userLoginRequest) {
        //1.按照用户名查询信息
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(User::getUsername, userLoginRequest.getUsername()).eq(User::getState, 0)
                .eq(User::getDeleteState, 0);

        User user = userMapper.selectOne(queryWrapper);

        //2.对查询结果进行非空校验
        if (user == null) {
            //打印日志
            log.error(ResultCode.FAILED_LOGIN.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_LOGIN));
        }

        //3.对密码进行校验
        String encryptPassword = MD5Utils.md5Salt(userLoginRequest.getPassword(), user.getSalt());

        if (!encryptPassword.equals(user.getPassword())) {
            //打印日志
            log.error(ResultCode.FAILED_LOGIN.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_LOGIN));
        }

        Map<String, Object> map = new HashMap<>();
        map.put("id",user.getId());
        map.put("name", user.getUsername());
        String token = JWTUtils.genToken(map);

        //登录成功, 但会用户信息
        log.info("登录成功, username: " + user.getUsername());
        return new UserLoginResponse(user.getId(), token);
    }

    @Override
    public UserSelectResponse selectById(Integer id) {
        //查询数据库 获取用户信息
        User user = userMapper.selectById(id);

        //转化
        UserSelectResponse userSelectResponse = BeanTransUtils.transUser(user);

        //返回结果
        return userSelectResponse;
    }

    @Override
    public void addOneArticleCountById(Integer id) {
        //查询对应的板块
        User user = userMapper.selectById(id);

        //判断
        if (user == null) {
            //打印日志
            log.error(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_IS_NULL));
        }

        //更新用户的发帖子数量
        User userUpdate = new User();
        userUpdate.setId(id);
        userUpdate.setArticleCount(user.getArticleCount() + 1);

        //更新数据库
        int row = userMapper.updateById(userUpdate);
        if (row != 1) {
            //打印日志
            log.error(ResultCode.FAILED_USER_ARTICLE_COUNT.toString() + ", 受影响的行数不等于1");
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }

        //打印日志
        log.info("更新用户发帖数量成功, user id = " + id);
    }

    @Override
    public void subOneArticleCountById(Integer id) {
        //查询用户详情
        User user = userMapper.selectById(id);

        if (user == null) {
            //打印日志
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", user id = " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //更新用户的发帖数量
        User userUpdate = new User();
        userUpdate.setId(id);
        userUpdate.setArticleCount(user.getArticleCount() - 1);
        userUpdate.setUpdateTime(new Date());

        //判断减1之后是否小于0
        if (userUpdate.getArticleCount() < 0) {
            //如果小于零则设置为0
            userUpdate.setArticleCount(0);
        }

        //更新数据库
        int row = 0;
        try {
            row = userMapper.updateById(userUpdate);
        } catch (Exception e) {
            //打印日志
            log.error(ResultCode.FAILED_USER_ARTICLE_COUNT.toString() + ", 受影响的行数不等于1");
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }

        if (row != 1) {
            //打印日志
            log.error(ResultCode.FAILED_USER_ARTICLE_COUNT.toString() + ", 受影响的行数不等于1");
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }

    }

    @Override
    public void modifyUserInfo(UserModifyRequest userModifyRequest) {
        //判断用户是否存在
        User existsUser = userMapper.selectById(userModifyRequest.getId());

        if (existsUser == null) {
            //打印日志
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //定义一个标志位
        Boolean flag = false;

        //定义一个专门用来更新的对象
        User userUpdate = new User();

        //设置用户id
        userUpdate.setId(userModifyRequest.getId());

        //对每一个参数进行校验
        //校验用户名
        if (userModifyRequest.getUsername() == null || !userModifyRequest.getUsername().equals(existsUser.getUsername())) {
            //进行用户名唯一校验
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.lambda().eq(User::getUsername, userModifyRequest.getUsername())
                    .eq(User::getState, 0)
                    .eq(User::getDeleteState, 0);
            User user = userMapper.selectOne(queryWrapper);

            if (user != null) {
                //打印日志
                log.error(ResultCode.FAILED_USER_EXISTS.toString());
                //抛出异常
                throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_EXISTS));
            }

            //数据库中没有该用户表示可以修改用户名
            userUpdate.setUsername(userModifyRequest.getUsername());

            //更新标志位
            flag = true;
        }



        //校验昵称
        if (userModifyRequest.getNickname() != null && !userModifyRequest.getNickname().equals(existsUser.getNickname())) {
            //更新昵称
            userUpdate.setNickname(userModifyRequest.getNickname());

            //更新标志位
            flag = true;
        }

        //校验性别
        if (userModifyRequest.getGender() != null && !userModifyRequest.getGender().equals(existsUser.getGender())) {
            //更新性别
            userUpdate.setGender(userModifyRequest.getGender());

            //校验合法性
            if (userModifyRequest.getGender() < 0 || userModifyRequest.getGender() > 2) {
                userUpdate.setGender((byte)2);
            }
            //更新标志位
            flag = true;
        }

        //校验邮箱
        if (userModifyRequest.getEmail() != null && !userModifyRequest.getEmail().equals(existsUser.getEmail())) {
            //更新邮箱
            userUpdate.setEmail(userModifyRequest.getEmail());

            //更新标志位
            flag = true;
        }

        //校验手机号
        if (userModifyRequest.getPhoneNum() != null && !userModifyRequest.getPhoneNum().equals(existsUser.getPhoneNum())) {
            //更新手机号
            userUpdate.setPhoneNum(userModifyRequest.getPhoneNum());

            //更新标志位
            flag = true;
        }

        //校验个人简介
        if (userModifyRequest.getRemark() != null && !userModifyRequest.getRemark().equals(existsUser.getRemark())) {
            //更新个人简介
            userUpdate.setRemark(userModifyRequest.getRemark());

            //更新标志位
            flag = true;
        }

        //判断是否需要更新
        if (flag == false) {
            //打印日志
            log.error(ResultCode.FAILED_USER_NOT_MODIFY.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_MODIFY));
        }

        //调用mapper执行更新
        int result = userMapper.updateById(userUpdate);

        if (result != 1) {
            //打印日志
            log.error(ResultCode.FAILED_USER_NOT_MODIFY.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_MODIFY));
        }

    }

    @Override
    public void modifyPassword(ModifyPasswordRequest modifyPasswordRequest) {
        //查询用户信息
        User existsUser = userMapper.selectById(modifyPasswordRequest.getId());

        //校验用户是否存在
        if (existsUser == null) {
            //打印日志
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //对老密码进行加密
        String oldPassword = MD5Utils.md5Salt(modifyPasswordRequest.getOldPassword(), existsUser.getSalt());

        //校验老密码是否正确
        if (!existsUser.getPassword().equals(oldPassword)) {
            //打印日志
            log.error(ResultCode.FAILED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED));
        }

        //生成一个盐值
        String salt = UUIDUtil.UUID_32();

        //生成新密码的密文
        String encryptPassword = MD5Utils.md5Salt(modifyPasswordRequest.getNewPassword(), salt);

        //创建一个更新的用户对象
        User userUpdate = new User();
        userUpdate.setId(modifyPasswordRequest.getId());
        userUpdate.setPassword(encryptPassword);
        userUpdate.setSalt(salt);
        userUpdate.setUpdateTime(new Date());

        //调用mapper执行更新
        int result = userMapper.updateById(userUpdate);

        if (result != 1) {
            //打印日志
            log.error(ResultCode.FAILED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED));
        }
    }

}
